<template>
  <div class="page">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="form">
      <el-form-item label-width="0" prop="name">
        <el-input v-model="form.name" placeholder="请输入内容" size="small">
          <template slot="prepend">
            接口名称
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label-width="0" prop="apiUrl">
        <el-input v-model="form.apiUrl" placeholder="请输入内容" size="small">
          <template slot="prepend">
            <el-select v-model="form.postType" size="small" style="width:120px" placeholder="请求方式">
              <el-option v-for="(item,index) in options" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <div class="title">
        Header
        <el-button size="mini" type="primary" @click="importJSON('header')">
          导入JSON
        </el-button>
      </div>
      <el-row v-for="(item,index) in headerJSON" :key="`header-${index}`" class="row-wrap">
        <el-col :span="6">
          <el-form-item label-width="10px">
            <el-input v-model="item.name" placeholder="请输入内容" size="small">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="10px">
            <el-input v-model="item.value" type="textarea" class="editor" autosize placeholder="请输入内容" size="small">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="10px">
            <el-input v-model="item.desc" placeholder="请输入描述" size="small">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">
        body
        <el-button size="mini" type="primary" @click="importJSON('body')">
          导入JSON
        </el-button>
      </div>
      <!-- {{ bodyJSON }} -->
      <div v-for="(item,index) in bodyJSON" :key="`body-${index}`" class="row-wrap">
        <el-row v-if="!item.type">
          <el-col :span="6">
            <el-form-item label-width="10px">
              <el-input v-model="item.name" placeholder="请输入内容" size="small">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="10px">
              <el-input v-model="item.value" type="textarea" class="editor" autosize placeholder="请输入内容" size="small">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="10px">
              <el-input v-model="item.desc" placeholder="请输入描述" size="small">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-else class="requestDataDiv">
          <div class="header-title">
            {{ item.name }}：
          </div>
          <el-row v-for="(ceil,ceilIndex) in item.value" :key="`ceil-${ceilIndex}`" class="row-wrap">
            <el-col :span="6">
              <el-form-item label-width="10px">
                <el-input v-model="ceil.name" placeholder="请输入内容" size="small">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label-width="10px">
                <el-input v-model="ceil.value" type="textarea" class="editor" autosize placeholder="请输入内容" size="small">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label-width="10px">
                <el-input v-model="ceil.desc" placeholder="请输入描述" size="small">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="title">
        返回样例
      </div>
      <el-form-item label-width="0" prop="result">
        <el-input v-model="form.result" class="result-input" :rows="5" type="textarea" autosize placeholder="请输入内容" size="small">
        </el-input>
      </el-form-item>
      <div class="title">
        接口说明
      </div>
      <el-form-item label-width="0" prop="desc">
        <el-input v-model="form.desc" :rows="5" type="textarea" placeholder="请输入内容" size="small">
        </el-input>
      </el-form-item>
      <div class="title">
        关联功能
      </div>
      <el-form-item label-width="0">
        <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="expanded" :default-checked-keys="defaultChecked" :props="defaultProps">
        </el-tree>
      </el-form-item>

      <el-form-item label-width="0">
        <el-button size="small" type="primary" native-type="submit" @click.prevent="submit">
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="请输入JSON" :visible.sync="headerDialog" width="50%">
      <json-editor v-model="form.headerJSON"></json-editor>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="headerDialog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="entry('header')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="请输入JSON" :visible.sync="bodyDialog" width="50%">
      <json-editor v-model="form.bodyJSON"></json-editor>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="bodyDialog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="entry('body')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { api } from '~/assets/utils'
import { Loading } from 'element-ui'
import _ from 'lodash'

export default {
  layout: 'project',
  data() {
    return {
      defaultChecked: [],
      expanded: [],
      headerJSON: [],
      bodyJSON: [],
      headerDialog: false,
      bodyDialog: false,
      options: ['POST', 'GET'],
      treeData: [],
      totalPage: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        name: [
          { required: true, message: '请输入接口名称', trigger: 'change' }
        ],
        apiUrl: [
          { required: true, message: '请输入接口地址', trigger: 'change' }
        ],
        result: [
          { required: true, message: '请输入接口返回样例', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请输入接口说明', trigger: 'change' }
        ]
      },
      form: {
        headerJSON: null,
        bodyJSON: null,
        postType: 'GET'
      }
    }
  },
  components: {
    // vueJsonEditor
  },
  methods: {
    transferArr(jsonStr) {
      const arr = []
      const obj = JSON.parse(jsonStr)
      if (obj.requestData) {
        //  obj.requestData = JSON.parse(obj.requestData)
      }
      for (const x in obj) {
        const ceil = {
          name: x,
          desc: ''
        }
        if (_.isObject(obj[x]) && !_.isArray(obj[x])) {
          const newArr = []
          const newObj = obj[x]
          for (const j in newObj) {
            newArr.push({
              name: j,
              value: _.isObject(newObj[j]) ? JSON.stringify(newObj[j]) : newObj[j],
              desc: ''
            })
          }
          ceil.value = newArr
          ceil.type = 'object'
        } else {
          ceil.value = _.isObject(obj[x]) ? JSON.stringify(obj[x]) : obj[x]
        }
        arr.push(ceil)
      }
      console.log(arr)
      return arr
    },
    transferJSON(arr) {
      const obj = {}
      arr.forEach(item => {
        if (_.isArray(item.value)) {
          const newObj = {}
          item.value.forEach(ceil => {
            newObj[ceil.name] = ceil.value
          })
          obj[item.name] = newObj
        } else {
          obj[item.name] = item.value
        }
      })
      return JSON.stringify(obj)
    },
    entry(type) {
      const jsonName = type === 'header' ? 'headerJSON' : 'bodyJSON'
      const dialogName = type === 'header' ? 'headerDialog' : 'bodyDialog'
      try {
        this[jsonName] = this.transferArr(this.form[jsonName])
        this[dialogName] = false
      } catch (err) {
        console.log(err)
        this.$message({
          type: 'warning',
          message: '请检查JSON格式'
        })
      }
    },
    importJSON(type) {
      const jsonName = type === 'header' ? 'headerJSON' : 'bodyJSON'
      const dialogName = type === 'header' ? 'headerDialog' : 'bodyDialog'
      this[dialogName] = true
      this.form[jsonName] = this.transferJSON(this[jsonName])
      console.log(this.form[jsonName])
    },
    submit() {
      const { projectId } = this.$route.params
      // const params = Object.assign(this.form, this.$route.params, this.$route.query)
      const checkList = this.$refs.tree.getCheckedNodes(true)
      this.form.subMenuId = checkList.map(item => item.id).join(',')
      this.form.menuId = _.uniq(checkList.map(item => item.parentId)).join(',')
      this.form.headerJSON = JSON.stringify(this.headerJSON)
      this.form.bodyJSON = JSON.stringify(this.bodyJSON)
      this.form.projectId = projectId
      if (!checkList.length) {
        return this.$message({
          type: 'warning',
          message: '请选择关联功能'
        })
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const loading = Loading.service({ fullscreen: true })
          this.$axios.post(api.updateApi, this.form).then((data) => {
            this.$message({
              type: 'success',
              message: data.msg
            })
            loading.close()
            this.$router.go(-1)
          })
        }
      })
    }
  },
  async mounted() {
    if (this.$route.query.id) {
      const res = await this.$axios.get(api.apiDetail, {
        params: {
          id: this.$route.query.id
        }
      })
      const { createdAt, updatedAt, ...others } = res.data
      this.form = this.$set(this, 'form', others)
      this.headerJSON = JSON.parse(this.form.headerJSON)
      this.bodyJSON = JSON.parse(this.form.bodyJSON)
      this.defaultChecked = this.form.subMenuId.split(',')
      console.log(this.defaultChecked)
    }
    const { projectId } = this.$route.params
    const res = await this.$axios.get(api.tree, { params: { projectId } })
    this.treeData = res.data
    this.expanded = res.data.map(item => item.id)
  }
}
</script>

<style lang='scss' scoped>
.result-input {
  /deep/ textarea {
    //font-weight: bold;
    background: #777;
    color: #fff;
    font-family: "Arial, Helvetica, sans-serif";
  }
}
.page {
  padding: 30px;
  /deep/ .el-input-group__prepend {
    width: 120px;
  }
  .editor /deep/ {
    textarea {
      font-family: Arial, Helvetica, sans-serif;
    }
  }
  .title {
    padding: 10px;
    background: #f1f1f1;
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    align-items: center;
  }
  .requestDataDiv {
    background: #fff;
    border-radius: 6px;
    padding-bottom: 5px;
    margin-bottom: 10px;
    border:1px dashed #f1f1f1;
    .header-title {
      padding: 10px;
    }
    /deep/ .el-row{
      padding-left: 15px;
    }
  }
  .row-wrap {
    .el-form-item {
      margin-bottom: 5px;
    }
  }
}
</style>
